package com.party.web.web.controller.member;

import com.google.common.collect.Lists;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.article.Article;
import com.party.core.model.article.ArticleType;
import com.party.core.model.channel.Channel;
import com.party.core.model.commune.CNotebook;
import com.party.core.model.commune.CNotebookType;
import com.party.core.model.subject.Subject;
import com.party.core.model.subject.SubjectApply;
import com.party.core.model.system.Dict;
import com.party.core.model.system.DictEnum;
import com.party.core.service.article.IArticleMemberService;
import com.party.core.service.article.IArticleService;
import com.party.core.service.channel.IChannelService;
import com.party.core.service.commune.ICNotebookService;
import com.party.core.service.commune.ICNotebookTypeService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.material.IMaterialMemberService;
import com.party.core.service.member.IMemberGroupPermissionService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.subject.ISubjectApplyService;
import com.party.core.service.subject.ISubjectService;
import com.party.core.service.system.IDictService;
import com.party.web.biz.article.ArticleBizService;
import com.party.web.biz.file.FileBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.article.ArticleOutput;
import com.party.web.web.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: party
 * @description: 素材管理
 * @author: Hua Qunhao
 * @create: 2019-12-10 11:17
 **/
@Controller
@RequestMapping("member/materialmgmt")
public class MaterialMgmtController {

    @Autowired
    private IArticleService articleService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private IDictService dictService;
    @Autowired
    private IArticleMemberService articleMemberService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private ArticleBizService articleBizService;
    @Autowired
    private IMaterialMemberService materialMemberService;
    @Autowired
    private IMemberGroupPermissionService memberGroupPermissionService;
    @Autowired
    private IChannelService channelService;
    @Autowired
    private ISubjectApplyService subjectApplyService;
    @Autowired
    private ISubjectService subjectService;
    @Autowired
    private ICNotebookService notebookService;
    @Autowired
    private ICNotebookTypeService notebookTypeService;


    protected static Logger logger = LoggerFactory.getLogger(MaterialMgmtController.class);

    /**
     * @Description:素材管理列表
     * @Param: [article, page, commonInput]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/12/10
     */
    @RequestMapping(value = "list")
    public ModelAndView materialmgmtList(Article article, Page page, CommonInput commonInput) {
        ModelAndView mv = new ModelAndView("member/material/materialList");
        page.setLimit(10);
        article.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        article.setArticleType(ArticleType.ARTICLE_TYPE_MATERIAL.getCode());
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        mv.addObject("input", commonInput);

        CurrentUser user = RealmUtils.getNewCurrentUser();
        List<CNotebook> cNotebooks = Lists.newArrayList();
        if (!user.isChild()) {
            cNotebooks = notebookService.list(null);
        } else {
            CNotebook notebook = new CNotebook();
            if (!Constant.MEMBER_XZGSADMIN.equals(user.getType())) {
                params.put("memberGroupUserId", user.getId());
                notebook.setMemberGroupUserId(user.getId());
                cNotebooks = notebookService.list(notebook);
            } else {
                cNotebooks = notebookService.webListPage(null, null);
            }
        }
        params.put("contentType", article.getContentType());
        params.put("materialType", article.getMaterialType());
        params.put("notebookId", article.getNotebookId());
        params.put("notebookTypeId", article.getNotebookTypeId());
        List<Article> articles = articleService.webMaterialListPage(article, params, page);
        List<ArticleOutput> articleOutputs = LangUtils.transform(articles, input -> {
            ArticleOutput articleOutput = ArticleOutput.transform(input);
            String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "article");
            // 详情二维码
            String fileName = "detail_" + input.getId();
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fileName);
            articleOutput.setQrCodeUrl(qrCodeUrl);

            if (StringUtils.isNotEmpty(input.getNotebookTypeId())) {
                CNotebookType cNotebookType = notebookTypeService.get(input.getNotebookTypeId());
                articleOutput.setNotebookTypeName(cNotebookType.getName());
                CNotebook notebook = notebookService.get(cNotebookType.getNotebookId());
                articleOutput.setNotebookName(notebook.getName());
            }
            return articleOutput;
        });
        mv.addObject("notebooks", cNotebooks);
        mv.addObject("article", article);
        mv.addObject("isChild", user.isChild());
        mv.addObject("articles", articleOutputs);
        mv.addObject("isXzgsAdmin", user.isXzgsAdmin());
        mv.addObject("page", page);
        return mv;
    }


    /**
     * @Description:发布（编辑）素材 视图
     * @Param: [id]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/12/10
     */
    @RequestMapping(value = "form")
    public ModelAndView materialmgmtForm(String notebookId, String notebookTypeId, String id) {
        CurrentUser user = RealmUtils.getNewCurrentUser();
        ModelAndView mv = new ModelAndView("member/material/materialForm");

        List<CNotebook> notebooks = null;
        if (user.isXzgsAdmin()) {
            notebooks = notebookService.webListPage(null, null);
        } else {
            notebooks = notebookService.list(null);
        }
        Article article = null;
        if (StringUtils.isNotEmpty(id)) {
            article = articleService.get(id);
            String content = StringUtils.unescapeHtml4Video2Iframe(article.getContent());
            article.setContent(content);
            notebookId = article.getNotebookId();
            notebookTypeId = article.getNotebookTypeId();
        }
        mv.addObject("notebooks", notebooks);
        mv.addObject("notebookId", notebookId);
        mv.addObject("notebookTypeId", notebookTypeId);
        mv.addObject("article", article);
        mv.addObject("isChild", user.isChild());
        mv.addObject("isXzgsAdmin", user.isXzgsAdmin());
        return mv;
    }

    /**
     * @Description: 素材保存
     * @Param: [article, result, members]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/10
     */
    @ResponseBody
    @RequestMapping(value = "save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult materialmgmtSave(Article article, BindingResult result) {
        String memberId = RealmUtils.getNewCurrentUser().getId();
        if (RealmUtils.getNewCurrentUser().isXzgsAdmin()) {
            memberId = RealmUtils.getNewCurrentUser().getPartnerId();
        }
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }
        try {
            articleBizService.materialmgmtSave(article, memberId);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存文章异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存文章异常");
        }
    }

    /**
     * @Description: 素材删除
     * @Param: [id]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/10
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        try {
            articleService.delete(id);
            materialMemberService.deleteByArticleId(id);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("素材删除异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("素材删除异常");
        }
    }


    /**
     * 跳转至详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "materialDetail")
    public ModelAndView articleDetail(String id, String applyId) {
        ModelAndView mv = new ModelAndView("member/material/materialDetail");
        Article article = articleService.get(id);
        if (StringUtils.isNotEmpty(article.getContent())) {
            article.setContent(StringUtils.unescapeHtml4Video2Iframe(article.getContent()));
        }
        String articleType = article.getArticleType();
        Dict dict = new Dict();
        dict.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        dict.setType(DictEnum.ARTICLE_TYPE.getCode());
        dict.setValue(articleType);
        Dict dictEntity = dictService.getByProperty(dict);
        if (dictEntity != null) {
            article.setArticleType(dictEntity.getLabel());
        }
        if (article.getChannel() != null) {
            Channel channel = channelService.get(article.getChannel().getId());
            article.setChannel(channel);
        }
        mv.addObject("article", article);
        if (StringUtils.isNotEmpty(applyId)) {
            SubjectApply subjectApply = subjectApplyService.get(applyId);
            mv.addObject("subjectApply", subjectApply);
            Subject subject = subjectService.get(subjectApply.getSubjectId());
            mv.addObject("subject", subject);
        }

        return mv;
    }
}
